import cloud from '@lafjs/cloud'
import { baiwangInvoice } from '@/uni/invoice/baiwangInvoiceUtils'
let dbName = "invoicing"

export default async function (ctx: FunctionContext) {
  //查询企业标识
  const { data } = await cloud.invoke("uni/invoice/queryUniqueSign_noauth", { ...ctx })

  const json_data = {
    "qyId": data.qyId,
    "ddlsh": ctx.body.ddlsh
  };

  let resp = await baiwangInvoice({
    data: json_data,
    url: "/cloud/queryOrder"
  })
  //console.log("开票状态", ctx.body.ddlsh, resp)

  //查找 ctx.body.ddlsh
  let res = await cloud.nw.db.findByWhereJson({
    dbName,
    whereJson: { ddlsh: json_data.ddlsh },
  });
  res.status = resp.status
  res._status = resp._status
  res.ycyy = resp.ycyy
  res.pdf = resp.pdf
  res.qdfphm = resp.qdfphm
  //如果开具成功，就把isInvoicing变成0
  if (resp.status == 2) {
    res.isInvoicing = 0
    //更新订单状态
    await updateOrder(ctx.body.ddlsh, 7)
  } else if (resp.status == 6) { //作废成功
    await updateOrder(ctx.body.ddlsh, 2)
  }

  //更新
  let query = { ...res }
  delete query._id
  await cloud.nw.db.update({
    dbName,
    whereJson: { _id: res._id },
    dataJson: query
  });

  return cloud.utils.requestReturn({ data: resp })
}

async function updateOrder(out_trade_no, status) {
  await cloud.nw.db.update({
    dbName: "web-order",
    whereJson: { out_trade_no },
    dataJson: { status }
  });
}